from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from .models import *

class UserRegView(APIView):
    def post(self,request):
        data = request.data
        ser_data = UserSerializer(data=data)
        if ser_data.is_valid():
            ser_data.save()
            return Response({'msg':'添加成功','code':200})
        else:
            return Response(ser_data.errors)
    def get(self,request):
        user_list = User.objects.all()
        user_ser = UserSerializer(user_list,many=True)
        return Response({'msg':'获取成功','code':200,'data':user_ser.data})



class UserLoginView(APIView):
    def post(self,request):
        data = request.data
        username = data['username']
        user_login = UserSerializer(data=data)
        if user_login.is_valid():
            name = User.objects.filter(username=username).first()
            data = UserSerializer(name).data
            return Response({'msg':'登录成功','code':200,'data':data})
        else:
            return Response({'code':400,'msg':'登陆失败'})



class GouWuView(APIView):
    def post(self,request):
        data = request.data
        gou_ser = GouWuSerializer(data=data)
        if gou_ser.is_valid():
            gou_ser.save()
            return Response({'code':200,'msg':'添加成功'})
        else:
            return Response({'code':400,'msg':'添加购物车失败'})

    def get(self,request):
        gou_wu = GouWu.objects.all()
        gouwu_data = GouWuSerializer(gou_wu,many=True).data
        return Response({'code':200,'msg':'获取购物车成功','data':gouwu_data})








